package com.herr.springboot.base.integration.extend;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.web.filter.OncePerRequestFilter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;

/**
 * 日志过滤器
 * @author herr05
 */
public class LogFilter extends OncePerRequestFilter {

    public static final Logger log= LoggerFactory.getLogger(LogFilter.class);

    private static final String API_BEGIN_TIME = "API_BEGIN_TIME";
    private static final String API_GUID = "API_GUID";

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        MDC.clear();
        // 设置开始时间和requestId，用于response时计算请求耗时和对应的requestId
        httpServletRequest.setAttribute(API_BEGIN_TIME, System.currentTimeMillis());
        log.info("LogFilter");

        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }

    public static String generateGUID(int size) {
        UUID uuid = UUID.randomUUID();
        return uuid.toString().replaceAll("-", "").substring(0, size);
    }

}
